package eu.webhib.frmwrk.jsf.utils;

import eu.webhib.frmwrk.jsf.exception.ExceptionUtil;
import eu.webhib.frmwrk.jsf.exception.FatalApplException;
import java.io.IOException;
import javax.faces.application.ProjectStage;
import javax.faces.context.FacesContext;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

/*
 * Helper methods in the JSF area
 */
public class JsfUtil {

   private static final Logger log = Logger.getLogger(JsfUtil.class);
   public static final String SESSION_EXCEPTION_ATTRIBUTE = "application.exception";

   private JsfUtil() {
   }

   /*
    * Useful helper methods
    */
   public static HttpServletRequest getRequest() {
      return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
   }

   public static HttpServletResponse getResponse() {
      return (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
   }

   public static Object getRequestAttr(String attrName) {
      return getRequest().getAttribute(attrName);
   }

   public static String getRequestParam(String paramName) {
      return getRequest().getParameter(paramName);
   }

   public static Long getRequestParamLong(String paramName) {
      String paramVal = getRequestParam(paramName);
      log.trace("getRequestParamLong: " + paramVal);
      try {
         return Long.parseLong(paramVal);
      } catch (Exception ex) {
         return null;
      }
   }

   public static boolean isGet() {
      return getRequest().getMethod().equals("GET");
   }

   public static HttpSession getSession() {
      assert (FacesContext.getCurrentInstance() != null);
      assert (FacesContext.getCurrentInstance().getExternalContext() != null);
      return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
   }

   public static HttpSession getSessionOrNull() {
      if (FacesContext.getCurrentInstance() == null
              || FacesContext.getCurrentInstance().getExternalContext() == null) {
         return null;
      }
      return getSession();
   }

   public static Object getSessionAttr(String attrName) {
      return getSession().getAttribute(attrName);
   }

   public static void setSessionAttribute(String attrName, Object value) {
      getSession().setAttribute(attrName, value);
   }

   public static void sendRedirect(String redirectUrl) {
      log.info("sendRedirect - redirect to: " + redirectUrl);
      try {
         FacesContext.getCurrentInstance().getExternalContext().redirect(redirectUrl);
      } catch (IOException ex) {
         log.fatal(ExceptionUtil.getStackTrace(ex));
         throw new FatalApplException(ex);
      }
   }

   public static boolean isProductionStage () {
      return FacesContext.getCurrentInstance().isProjectStage(ProjectStage.Production);
   }
}
